package cn.com.tpqn;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class QnSignUitl {
	private static final Log log = LogFactory.getLog(QnSignUitl.class);

	private static final String CONTENT_CHARSET = "UTF-8";

	private static final String HMAC_ALGORITHM = "HmacSHA1";

	public static String sign(String signStr, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {

		log.debug("QnSignUitl Param signStr:" + signStr + " secret:" + secret);
		String sig = null;
		Mac mac = Mac.getInstance(HMAC_ALGORITHM);
		SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac.getAlgorithm());

		mac.init(secretKey);
		byte[] hash = mac.doFinal(signStr.getBytes(CONTENT_CHARSET));

		sig = new String(Base64.getEncoder().encodeToString(hash));

		log.debug("QnSignUitl Return sig:" + sig);

		return sig;
	}
}